package com.sunlee.admin.api.module.job.task;

import com.sunlee.admin.api.module.job.dto.GeneratePptTaskDto;
import com.sunlee.admin.api.module.job.template.GeneratePptTemplate;
import com.sunlee.admin.api.module.job.template.TemplateFactory;
import com.sunlee.admin.api.module.job.template.context.GeneratePptContext;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.utils.EnvUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 解析构建新PPT
 *
 * @author sunulee
 */
@Component("generatePptTask")
public class GeneratePptTask implements ITask {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 防止重复执行
     */
    private static boolean isRun = false;

    @Override
    public void run(String params) {
        if (EnvUtil.isPro()) {
            return;
        }

        logger.info("generatePptTask定时任务正在执行，参数为：{}", params);

        if (isRun) {
            logger.warn("generatePptTask定时任务不可重复执行");
            return;
        }

        isRun = true;
        try {
            start(validaDTO(params));
        } finally {
            isRun = false;
            logger.info("generatePptTask定时任务执行结束");
        }

    }

    private void start(GeneratePptTaskDto dto) {

        GeneratePptTemplate generatePptTemplate = TemplateFactory.getGeneratePptTemplateByCode(dto.getSource());

        GeneratePptContext context = new GeneratePptContext();
        context.setDto(dto);

        generatePptTemplate.process(context);
    }

    private GeneratePptTaskDto validaDTO(String params) {
        GeneratePptTaskDto dto = validaParseParam(params, GeneratePptTaskDto.class);
        if (Objects.isNull(dto.getSource()) || dto.getSource() < 0) {
            throw new BusinessException(ErrorCodeEnum.PARAM_NOT_COMPLETE);
        }
        return dto;
    }
}
